<template>
  <el-dropdown class="btn" 
    :loading="loading" 
    @click="exportExcel"  
    @command="handleCommand" 
    split-button
    size="medium"
    type="primary">
    <el-icon style="icon"><elementDownload/></el-icon> 
    <span style="icon-font">导出</span>
    <template #dropdown>
      <el-dropdown-menu>
      <el-dropdown-item command="csv">导出Csv文件</el-dropdown-item>
      <el-dropdown-item command="xlsx">导出Excel文件</el-dropdown-item>
    </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script lang="ts">
import { reactive, toRefs } from "vue";
import XLSX from 'xlsx'
export default({
  name: 'BtnExport',
  props: {
    columns: {
      type: Array,
      default: () => []
    },
    data: {
      type: Array,
      default: () => {
        return []
      }
    },
    title: {
      type: String,
      default: () => {
        return '数据导出'
      }
    },
  },
  setup(props: any) {
    const state = reactive({
			loading: true,
		})

    const getExcelData = () => {
      // 获取数据
      let exportColumns = props.columns
      let exportData = props.data
      let tableColumns = []
      let tableColumnsTag = []
      for (let i = 0; i < exportColumns.length; i++) {
        tableColumns.push(exportColumns[i].label)
        tableColumnsTag.push(exportColumns[i].prop)
      }
      let mainArr = []
      for (let j = 0; j < exportData.length; j++) {
        let arr: any[] = []
        tableColumnsTag.forEach((tag)=>{
          if(Object.keys(exportData[j]).includes(tag)){
            arr.push(exportData[j][tag])
          }else{
            arr.push(null)
          }
        })
        mainArr.push(arr)
      }
      return [tableColumns].concat(mainArr);  //数据，一定注意需要时二维数组
    }

    const exportTable = (type: string='xlsx') => {
      state.loading = true
      let filename = props.title + '.' + type; //文件名称
      let data = getExcelData()
      let ws_name = "Sheet1"; //Excel第一个sheet的名称
      let wb = XLSX.utils.book_new()
      let ws = XLSX.utils.aoa_to_sheet(data)
      XLSX.utils.book_append_sheet(wb, ws, ws_name)  //将数据添加到工作薄
      XLSX.writeFile(wb, filename); //导出Excel
      state.loading = false
    }

    const exportExcel = () => {
      exportTable()
    }
    const handleCommand = (command: any) => {
      exportTable(command)
    }
    return { 
      ...toRefs(state),
      exportExcel,
      handleCommand,
    }
  }
})
</script>

<style lang="scss" scoped>
.btn {
  margin-left: 10px;
}
.icon{
  margin-left: -5px;
  text-align: center;
  vertical-align: middle;
  display: inline-block;
}
.icon-font{
  text-align: center;
  vertical-align: middle;
  display: inline-block;
}
</style>
